package com.cmbc.cos.cbs.wsclient.util;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.handler.Handler;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.HandlerRegistry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RPCHandlerUtil {

    static Logger log = LoggerFactory.getLogger(RPCHandlerUtil.class);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void registerHandler(Service service, Class<? extends Handler> handlerClass) {
        try {
            HandlerRegistry hr = service.getHandlerRegistry();

            Iterator ports = service.getPorts();
            while (ports.hasNext()) {
                QName portName = (QName) ports.next();
                List hc = hr.getHandlerChain(portName);
                HandlerInfo hi = new HandlerInfo();
                hi.setHandlerClass(handlerClass);
                hc.add(hi);
            }
        }
        catch (Exception e) {
            log.error("register handler error", e);
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void registerHandler(Service service, String portName, Class<? extends Handler> handlerClass) {
        try {
            List hc = service.getHandlerRegistry().getHandlerChain(new QName(portName));
            HandlerInfo hi = new HandlerInfo();
            hi.setHandlerClass(handlerClass);
            hc.add(hi);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
